package com.springboot.uav.controller;

import com.springboot.uav.dto.FeedbackDto;
import com.springboot.uav.entity.Feedback;
import com.springboot.uav.entity.Result;
import com.springboot.uav.service.FeedbackService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.NotBlank;

import java.util.List;

@RestController
@RequestMapping("/feedback")
@Tag(name = "反馈接口", description = "用户反馈相关接口")
public class FeedbackController {

    @Autowired
    private FeedbackService feedbackService;


    @Operation(summary = "用户自助留言", description = "用户提交反馈信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "反馈提交成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "500", description = "内部服务器错误")
    })
    @PostMapping("/submit")
    public Result submitFeedback(@RequestBody FeedbackDto feedbackDto) {

        if (feedbackDto.getMessage() == null || feedbackDto.getMessage().trim().isEmpty()) {
            return Result.error(400, "反馈信息不能为空");
        }


        boolean submitted = feedbackService.submitFeedback(feedbackDto);
        if (submitted) {
            return Result.success("反馈提交成功");
        } else {
            return Result.error(400, "反馈提交失败");
        }
    }


    @Operation(summary = "查询历史留言", description = "用户查询自己的历史留言")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功返回历史留言"),
            @ApiResponse(responseCode = "400", description = "请求参数无效"),
            @ApiResponse(responseCode = "401", description = "未授权访问"),
            @ApiResponse(responseCode = "500", description = "内部服务器错误")
    })
    @GetMapping("/history")
    public Result getFeedbackHistory(@RequestParam String userId) {
        try {

            int id = Integer.parseInt(userId);
            if (id <= 0) {
                return Result.error(400, "用户ID必须为正整数");
            }
            List<Feedback> feedbackList = feedbackService.getFeedbackHistory(id);
            return Result.success(feedbackList);
        } catch (NumberFormatException e) {

            return Result.error(400, "用户ID必须为正整数");
        }
    }


    @Operation(summary = "修改反馈状态", description = "管理员修改反馈状态")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "状态修改成功"),
            @ApiResponse(responseCode = "400", description = "请求参数无效"),
            @ApiResponse(responseCode = "404", description = "反馈不存在"),
            @ApiResponse(responseCode = "500", description = "内部服务器错误")
    })
    @PutMapping("/{id}/status")
    public Result updateFeedbackStatus(@PathVariable String id, @RequestParam String status) {

        if (!isPositiveInteger(id)) {
            return Result.error(400, "反馈ID必须是正整数");
        }


        Long feedbackId = Long.parseLong(id);


        if (!isValidStatus(status)) {
            return Result.error(400, "状态参数无效，只能为'已处理'或'未处理'");
        }

        boolean updated = feedbackService.updateFeedbackStatus(feedbackId, status);
        if (updated) {
            return Result.success("状态修改成功");
        } else {
            return Result.error(404, "反馈不存在");
        }
    }


    private boolean isValidStatus(String status) {
        return "已处理".equals(status) || "未处理".equals(status);
    }


    @Operation(summary = "添加管理员回复", description = "管理员回复用户的反馈")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "回复成功"),
            @ApiResponse(responseCode = "400", description = "请求参数无效"),
            @ApiResponse(responseCode = "404", description = "反馈不存在"),
            @ApiResponse(responseCode = "500", description = "内部服务器错误")
    })
    @PutMapping("/{id}/response")
    public Result addFeedbackResponse(@PathVariable String id, @RequestParam String response) {

        if (!isPositiveInteger(id)) {
            return Result.error(400, "反馈ID必须是正整数");
        }


        Long feedbackId = Long.parseLong(id);

        if (response == null || response.trim().isEmpty()) {
            return Result.error(400, "回复内容不能为空");
        }


        boolean responded = feedbackService.addFeedbackResponse(feedbackId, response);
        if (responded) {
            return Result.success("回复成功");
        } else {
            return Result.error(404, "反馈不存在");
        }
    }




    @Operation(summary = "分页查询所有反馈", description = "管理员分页查询所有反馈信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "400", description = "分页参数无效"),
            @ApiResponse(responseCode = "500", description = "内部服务器错误")
    })
    @GetMapping("/all")
    public Result getAllFeedbacks(
            @RequestParam(defaultValue = "1") String page,
            @RequestParam(defaultValue = "10") String size
    ) {

        if (!isPositiveInteger(page) || !isPositiveInteger(size)) {
            return Result.error(400, "分页参数无效：页数和每页大小必须是正整数");
        }


        int pageNumber = Integer.parseInt(page);
        int pageSize = Integer.parseInt(size);

        return Result.success(feedbackService.getAllFeedbacks(pageNumber, pageSize));
    }

    private boolean isPositiveInteger(String value) {
        try {
            int number = Integer.parseInt(value);
            return number > 0;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}